package com.example.mediamoudle.utlis

import android.content.Context
import android.media.MediaCodec
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import android.util.Log
import android.util.TypedValue
import androidx.annotation.RequiresApi
import java.io.File
import java.nio.ByteBuffer

class MediaUtils {
    companion object{
        @JvmStatic
        fun getVideoDuration(context: Context, videoPath: String?): Long {
            val retriever = MediaMetadataRetriever()
            retriever.setDataSource(context, Uri.fromFile(File(videoPath)))
            val duration =
                retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLong()?:0
            retriever.release()
            return duration
        }
    }
}

/**
 * dp转px
 *
 * @param context
 * @param dp
 * @return
 */
fun Context.dp2px(dp: Float): Float {
    return TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        dp, resources.displayMetrics
    )
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun MediaCodec.dequeueValidInputBuffer(timeOutUs: Long): InputCodeCData {
    val inputBufferId = dequeueInputBuffer(timeOutUs)
    if (inputBufferId >= 0) {
        return InputCodeCData(inputBufferId, getInputBuffer(inputBufferId))
    }
    return InputCodeCData(inputBufferId, null)
}
fun MediaCodec.disposeOutput(bufferInfo: MediaCodec.BufferInfo, defTimeOut: Long,
                             endStream: () -> Unit = {},
                             formatChanged: () -> Unit = {},
                             render: (outputBufferId: Int) -> Unit) {
    //  获取可用的输出缓存队列
    val outputBufferId = dequeueOutputBuffer(bufferInfo, defTimeOut)
    Log.d("disposeOutput", "output buffer id : $outputBufferId ")
    when {
        outputBufferId >= 0 -> {
            // 2019/2/12-22:55 and是位运算 &，转换为二进制进行“与”运算.位数不匹配则都为0
            if ((bufferInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                // 2019/2/12-22:59 bufferInfo无可用缓存
                endStream.invoke()
            }
            render.invoke(outputBufferId)
        }
        outputBufferId == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> formatChanged.invoke()
    }
}
data class InputCodeCData(val id: Int, val inputBuffer: ByteBuffer?)